<template>
  <div>
    <el-row>
      <el-col :span="24" align="right">
<!--        <el-button type="primary" @click="uploadBox()" :disabled="isDisabled" v-limit="upload">上传附件</el-button>-->
      </el-col>
    </el-row>
    <Table :tableArr="fliestList" :pagination="data.page" :columns="data.columns" :isCheckbox="true"
           :total="fliestList.length" :dataSources="true" :fixed="true">
      <template #operate="{ row }">
        <el-button size="small" @click="goLook(row)">预览</el-button>
        <el-button size="small" type="primary" v-if="row.fileId" @click="handleDownload(row)" :disabled="isDisabled"
                   v-limit="download">下载</el-button>
<!--        <el-button size="small" type="danger" @click="handleDelete(row)" :disabled="isDisabled"-->
<!--                   v-limit="fileDelete">删除</el-button>-->
      </template>
    </Table>

    <el-dialog v-model="data.uploadDialog" append-to-body width="50%" top="10vh" :show-close="false"
               :close-on-click-modal="false" destroy-on-close>
      <template #title>
        <div class="my-header">
          <el-tabs v-model="data.activeName" class="demo-tabs">
            <el-tab-pane label="上传文件" name="first">
              <el-form :model="form" ref="ruleFormRef" :rules="rules" status-icon label-position="right"
                       label-width="90px" :inline="true" class="demo-form-inline">
                <el-row>
                  <el-col :span="13" v-if="filesTypeFlag">
                    <el-form-item label="文件类型" prop="busTypeName">

                      <SelectOption :selectValue="form.busTypeName" :options="data.options" @change-value="changeValue">
                      </SelectOption>
                    </el-form-item>
                  </el-col>
                  <el-col :span="13">
                    <el-form-item label="文件">
                      <el-upload v-model:file-list="fileList" class="upload-demo" :headers="headers"
                                 action="/fastDfs/file/upload" multiple :before-upload="beforeAvatarUpload"
                                 :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :limit="3"
                                 :on-exceed="handleExceed" :on-success="handleSuccess" :on-change="handleChange">
                        <el-button type="primary">上传文件</el-button>
                        <template #tip>
                          <div class="el-upload__tip">
                          </div>
                        </template>
                      </el-upload>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetFields">关闭</el-button>
          <el-button type="primary" @click="save()">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { downloadByUrl } from '@/views/science/api/common'
import common from '@/views/science/common/common.json'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/table.vue'
import { tips } from '@/views/science/components/tips/tips'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { computed, nextTick, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'

export default {
  components: {
    Table,
    SelectOption,
  },
  emits: {
    dataChange: null,
    filesParams: null,
  },
  props: {
    files: {
      type: Array,
      required: true,
    },
    filesTypeFlag: {
      type: Boolean,
      default: true,
    },
    isExamine: {//考核页面
      type: Boolean,
      default: false,
    },
    isDisabled: {//是否禁用
      type: Boolean,
      default: false,
    },
    download: {
      type: String,
      default: '',
    },
    upload: {
      type: String,
      default: '',
    },
    fileDelete: {
      type: String,
      default: '',
    },
  },
  setup(props, { emit }) {
    const store = useStore()
    const loading = ref(false)
    let data = reactive({
      activeName: ref('first'),
      columns: props.isExamine ? common.examineTypeName : props.filesTypeFlag ? common.platformFileHeader : common.platformFileHeaderNobusTypeName,//有的地方没有文件类型
      page: {
        page: 1,
        limit: 10,
        total: 0,
      },
      options: computed(() => store.state.technologyStrength.fileTypeList),
      uploadDialog: false,
    })

    const fliestList = ref(props.files)


    watch(props, (newValue, oldValue) => {
      fliestList.value = newValue.files
    });

    const form = reactive({
      fileId: '',
      fileName: "",
      fileSize: "",
      busTypeName: '',
      busTypeId: '',
      fileType: "",
      filePath: "",
    })

    const changeValue = (item) => {
      form.busTypeId = item.itemValue
      form.busTypeName = item.itemText
    }

    const rules = reactive({})

    const handleDownload = async (row) => {
      // row.filePath = "10,25,51,180/o1dkeptfi1e/FTP/公司文档软件著权/软著-天空地-体化公路边坡地质灾害监则预警系/18(219,1,29) AF11912301687140001 1.pdf"
      // console.log('rowrow',row.filePath.includes('o1dkeptfi1e'));
      if (!row.filePath.includes('o1dkeptfi1e')) {
        await downloadByUrl(row.fileId, row.fileName)
      } else {
        var oA = document.createElement('a');
        oA.download = row.fileName; // 设置下载的文件名
        oA.href = row.filePath;
        document.body.appendChild(oA);
        oA.click();
        oA.remove();
      }
    }
    const handleDelete = async (row) => {
      // if (row.id) {
      //   let res = await delectFiles(row.id)
      //   if (res.data.success) {
      //     emit('dataChange')
      //   }
      // } else {
      //   var index = fliestList.value.indexOf(row);
      //   if (index > -1) {//大于0 代表存在，
      //     fliestList.value.splice(index, 1);//存在就删除
      //   }
      // }
      var index = fliestList.value.indexOf(row);
      if (index > -1) {//大于0 代表存在，
        fliestList.value.splice(index, 1);//存在就删除
      }
    }

    const uploadBox = () => {
      data.uploadDialog = true
      const cbData = {
        busTypeName: [
          { required: true, message: '请选择文件类型', trigger: 'change' },
        ]
      }
      Object.assign(rules, cbData)
    }

    const fileList = ref<typeof UploadUserFile[]>([])

    const beforeAvatarUpload: typeof UploadProps['beforeUpload'] = (rawFile) => {
      loading.value = true
    }

    const handleChange: typeof UploadProps['onChange'] = (uploadFile, uploadFiles) => {
      console.log(uploadFile, uploadFiles)
      form.fileSize = uploadFile.size
      form.fileName = uploadFile.name
      fileList.value = uploadFiles
    }

    const handleSuccess: typeof UploadProps['onSuccess'] = (uploadFile) => {
      if (uploadFile.code == 200) {
        tips('上传成功', 'success')
        console.log(uploadFile)
        form.filePath = uploadFile.data.path
        form.fileType = uploadFile.data.type
        form.fileId = uploadFile.data.fileId
        loading.value = false
      } else {
        tips('上传失败', 'error')
      }
    }

    const handleError: typeof UploadProps['onError'] = (uploadFile) => {
      tips('上传失败', 'error')
    }

    const handleRemove: typeof UploadProps['onRemove'] = (file, uploadFiles) => {
      fileList.value.splice(fileList.value.indexOf(file), 1)
      console.log(file, uploadFiles)
    }

    const handlePreview: typeof UploadProps['onPreview'] = (uploadFile) => {
      console.log(uploadFile)
    }

    const beforeRemove: typeof UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
      console.log(1111)
    }

    const handleExceed: typeof UploadProps['onExceed'] = (files, uploadFiles) => {
      ElMessage.warning(
          `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
          } totally`
      )
    }

    const ruleFormRef = ref()
    const resetFields = () => {
      data.uploadDialog = false;
      fileList.value = [];
      ruleFormRef.value?.resetFields?.();
    }
    const save = async () => {
      await ruleFormRef.value.validate((valid, fields) => {
        if (loading.value) return tips('文件正在上传，请稍后', 'warning')
        if (valid) {
          const arr = fileList.value
          console.log(arr)
          if (arr.length == 0) return tips('请上传文件', 'warning')
          arr.map((item) => {
            let obj = {
              fileName: item.name,
              fileSize: item.size,
              busTypeName: form.busTypeName,
              busTypeId: form.busTypeId,
              fileType: item.response.data.type,
              filePath: item.response.data.path,
              fileId: item.response.data.fileId
            }
            if (JSON.stringify(fliestList.value).indexOf(JSON.stringify(obj)) == -1) {
              fliestList.value.push(obj)
            } else {
              tips('不可添加相同文件', 'warning')
            }
          })
          Object.keys(form).forEach((key) => {
            form[key] = ''
          })

          fileList.value = []

          Object.keys(rules).forEach((key) => {
            rules[key] = ''
          })

          emit('filesParams', fliestList)
          nextTick(resetFields)

        } else {
          console.log('校验失败')
        }
      })
    }
    const goLook = (row) => {
      console.log('goLook', row);
      // window.open("http://www.pfile.com.cn/api/profile/onlinePreview?url="+encodeURIComponent(row.filePath));
      if ([
        'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff', 'pdf'].
      indexOf(row.fileType.toLowerCase()) !== -1) {
        window.open(row.filePath)
      } else {
        tips('word,excel,zip等文件无法预览，请前往下载', 'warning')
      }
    }
    const cookie = () => localStorage.getItem('token')
    // eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsIm9yZ1R5cGUiOiJleHRlcm5hbCIsIm9yZ05hbWUiOiLkuK3lkqjmlbDmja7mnInpmZDlhazlj7giLCJjcmVhdGVkIjoxNjkzNDUwNDQ2MDUwLCJjTmFtZSI6IueuoeeQhuWRmCIsImV4cCI6MTcyNDk4NjQ0NiwidXNlcmlkIjoiNCIsInRlbmFudCI6IjEiLCJvcmdJZCI6IjEzNjMwIn0.-R5al5iis5shOri5g-afCnaMpycGAnztvkDb3WZnj9YYs-me4XhHo78OglV7fqlcLu8qDNSdkEpoGDg96gPN2w
    return {
      loading,
      data,
      goLook,
      form,
      fliestList,
      handleRemove,
      handlePreview,
      beforeRemove,
      handleExceed,
      rules,
      ruleFormRef,

      changeValue,
      uploadBox,
      handleDownload,
      handleDelete,
      headers: {
        Authorization: 'Bearer ' + cookie(),
      },
      beforeAvatarUpload,
      handleChange,
      handleSuccess,
      handleError,
      fileList,
      save,
      resetFields
    }
  },
}
</script>

<style scoped lang="scss"></style>
